package com.liwujie.controller;


import com.liwujie.BO.AuthAccountInVerifyBO;
import com.liwujie.VO.TokenInfoVO;
import com.liwujie.core.bean.ResultBean;
import com.liwujie.core.controller.BaseController;
import com.liwujie.model.AuthAccount;
import com.liwujie.service.IAuthAccountService;
import com.liwujie.token.TokenTemplate;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 统一账户信息 前端控制器
 * </p>
 *
 * @author liwujie
 * @since 2025-04-14
 */
@RestController
@RequestMapping("/api")
@Api(tags = "登录接口")
public class AuthAccountController extends BaseController {
    @Autowired
    private IAuthAccountService iAuthAccountService;

    @Autowired
    private TokenTemplate tokenTemplate;
    @PostMapping("/user/login")
    @Operation(summary = "账号密码" , description = "通过账号登录，还要携带用户的类型，也就是用户所在的系统")
    public ResultBean<TokenInfoVO> login(@RequestBody AuthAccountInVerifyBO authAccountInVerifyBO) {

        //1验证用户名和密码
        AuthAccount authAccount = iAuthAccountService.verifyAccount(authAccountInVerifyBO.getUsername(), authAccountInVerifyBO.getSysType());
        //验证账户是否存在
        if (authAccount == null){
            return fail("用户不存在");
        }
        //验证密码是否正确
        if (!authAccount.getPassword().equals(authAccountInVerifyBO.getPassword())) {
            return fail("密码错误");
        }
        //验证账户是否禁用
        if (authAccount.getStatus() == 0) {
            return fail("账户已禁用");
        }
        //生成token
        // 5. 生成Token
        Map<String, Object> payload = new HashMap<>();
        payload.put("uid", authAccount.getUid());
        payload.put("username", authAccount.getUsername());
        payload.put("sysType", authAccount.getSysType());
        payload.put("userId", authAccount.getUserId());
        payload.put("tenantId", authAccount.getTenantId());
        payload.put("isAdmin", authAccount.getIsAdmin());
        String accessToken = tokenTemplate.generateToken(payload);

        //6 构建返回结果
        TokenInfoVO tokenInfoVO = new TokenInfoVO();
        tokenInfoVO.setTokenType("Bearer");
        tokenInfoVO.setAccessToken(accessToken);
        tokenInfoVO.setExpiresIn((int) (tokenTemplate.getProperties().getValidTime() / 1000));

        return success("登录成功", tokenInfoVO);


    }

}
